//
//  ZZCollectColorTool.m
//  ZZBlue
//
//  Created by stonesMonkey on 2017/10/1.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZZCollectColorTool.h"
#define kCollectModelKey @"ZZCollectColorToolKey"
#define kCollectPath @"CollectColorTool.plist"

@implementation ZZCollectColorTool

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    
    static id listGroupModel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        listGroupModel = [super allocWithZone:zone];
        
    });
    
    return listGroupModel;
}


- (void)save {
    
    //准备路径:
    NSString *path = NSHomeDirectory();
    NSLog(@"%@",path);
    
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",kCollectPath]];
    //1:准备存储数据的对象
    NSMutableData *data = [NSMutableData data];
    //2:创建归档对象
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //3:开始归档
    [archiver encodeObject:self.group forKey:kCollectModelKey];
    //4:完成归档
    [archiver finishEncoding];
    //5:写入文件当中
    BOOL result = [data writeToFile:path atomically:YES];
    if (result) {
        
        // 写入成功
    }
}

- (ZZCollectColorGroup *)group {
    
    
    if (!_group) {
        
        // 从数据中拿
        NSString *path = NSHomeDirectory();
        path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",kCollectPath]];
        NSData *myData = [NSData dataWithContentsOfFile:path];
        //创建反归档对象
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:myData];
        //反归档
        ZZCollectColorGroup* listGroupModel = [unarchiver decodeObjectForKey:kCollectModelKey];
        //完成反归档
        [unarchiver finishDecoding];
        if (listGroupModel == nil) {

            listGroupModel = [ZZCollectColorGroup new];
            listGroupModel.colors = [NSMutableArray array];
            listGroupModel.reacts = [NSMutableArray array];
             _group = listGroupModel;
               [self save];
        }


        _group = listGroupModel;

    }
    
    return _group;
}



@end
